<template>
  <Table filter v-bind="tableOpts" v-on="tableEvent" :key="componentKey">
    <template #operator>
      <div class="operator-wrap">
        <modifyInventory ref="dialogRef" @change="fetchCurrentTable"/>
        <div style="display: flex">
          <!--          <el-button size="small" type="primary"-->
          <!--                     @click="exportDialog"-->
          <!--          >-->
          <!--            导入库存-->
          <!--          </el-button>-->
          <!--          <el-upload-->
          <!--              :show-file-list="false"-->
          <!--              :headers="headers"-->
          <!--              :action="`${$apiHost}/material/inventory/import/execl`"-->
          <!--              :on-success="onSuccess"-->
          <!--              :on-error="onError"-->
          <!--              :before-upload="onBefore"-->
          <!--          >-->
          <!--            <el-button size="small" type="primary">-->
          <!--              导入库存-->
          <!--              <span v-if="loading" class="el-icon-loading"></span>-->
          <!--            </el-button>-->
          <!--          </el-upload>-->
          <el-dropdown @command="defaultInventory">
            <el-button  v-if="authority.includes(1251)" type="primary" size="small" style="margin-left: 10px">
              导出库存<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="item in areaList" v-model="item.area" :command="item.area" :key="item.area">
                {{ item.areaName }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
      <!--      <el-dialog-->
      <!--          :close-on-click-modal="false"-->
      <!--          title="修改库位"-->
      <!--          :visible.sync="openWare"-->
      <!--          width="30%"-->
      <!--          center-->
      <!--          :show-close="false"-->
      <!--          :before-close="handleClose">-->
      <!--        <el-button size="small" type="primary" style="margin: 0 80px 5px 80px;"-->
      <!--                   @click="pushWareList">增加库位-->
      <!--        </el-button>-->

      <!--        <div style="display: flex;align-items: center;margin-top: 10px" v-for="(item,index) in addWareList"-->
      <!--             :key="'addWareList'+index">-->
      <!--        <div style="display: flex;align-items: center;margin-top: 10px">-->
      <!--          <span>库位列表：</span>-->
      <!--          <el-select v-model="warehousePosition" filterable-->
      <!--                     placeholder="请选择" style="width: 350px;margin-left: 20px" size="small">-->
      <!--            <el-option v-for="item in positionList" :key="item"-->
      <!--                       :value="item"-->
      <!--                       :label="item">-->
      <!--            </el-option>-->
      <!--          </el-select>-->
      <!--          &lt;!&ndash;          <el-link style="font-size: 12px;width: 80px"&ndash;&gt;-->
      <!--          &lt;!&ndash;                   @click="deleteProduce(addWareList,index)">删除&ndash;&gt;-->
      <!--          &lt;!&ndash;          </el-link>&ndash;&gt;-->
      <!--        </div>-->
      <!--        <span slot="footer" class="dialog-footer">-->
      <!--    <el-button @click="openWare = false">取 消</el-button>-->
      <!--    <el-button type="primary" @click="submit">确 定</el-button>-->
      <!--        </span>-->
      <!--      </el-dialog>-->
      <el-dialog
          title="修改预警值"
          :close-on-click-modal="false"
          :visible.sync="openWarning"
          width="25%"
          center
          :show-close="false"
          :before-close="handleClose">
        <div style="display: flex;align-items: center;margin-top: 10px">
          <span>库存警告值：</span>
          <el-input-number v-model="warningNum" :min="0">
          </el-input-number>
        </div>
        <div style="display: flex;align-items: center;margin-top: 10px">
          <span>紧急补货值：</span>
          <el-input-number v-model="exigencyNum" :min="0">
          </el-input-number>
        </div>
        <span slot="footer" class="dialog-footer">
    <el-button @click="openWarning = false">取 消</el-button>
    <el-button type="primary" @click="submitWarning">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog :visible.sync="dialogVisible" v-if="dialogVisible" center top="10px" width="30%" title="导入库存">
        <div style="margin-top: 20px"><span style="font-size: 12px"><span
            style="color: red">*</span>凭证：复制粘贴即可上传图片</span></div>
        <div class="div" style="display: flex; align-items: center">
          <div
              v-for="(v, i) in preSalesImg"
              style="display: flex; align-items: center; margin-right: 10px"
          >
            <el-image
                :key="i"
                style="width: 50px; height: 50px"
                ref="preview"
                :src="host + v"
                :preview-src-list="[host + v]"
            >
            </el-image>
            <div @click="deletePic(i)">
              <el-icon name="delete"></el-icon>
            </div>
          </div>
        </div>
        <div style="margin-top: 20px">
          <span style="color: red">*</span>上传文件：
          <el-upload
              class="upload-demo"
              drag
              :show-file-list="false"
              :headers="headers"
              :action="`${$apiHost}/material/inventory/import/execl`"
              :on-success="onSuccess"
              :on-error="onError"
              :before-upload="onBefore"
              multiple>
            <!--          :data="uploadData"-->
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传excel文件，且不超过500kb</div>
          </el-upload>
        </div>
      </el-dialog>
    </template>
  </Table>
</template>

<script>
import {mapState} from "vuex";
import modifyInventory from "./components/modifyInventory.vue";
import tableMixins from "@/mixins/tableMixins.vue";
import * as XLSX from 'xlsx-js-style';
import axios from "axios";
import store from "../../store";
import quinn from "../../utils/quinn";

export default {
  name: "InventoryDetail",
  mixins: [tableMixins],
  components: {
    modifyInventory,
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      warehousePosition: [],
      areaList: [],
      componentKey: 0,
      preSalesImg: [],
      preSalesImgList: [],
      uploadData: {},
      addWareList: [],
      authority:[],
      positionList: [],
      apiName: "getInventory",
      openWare: false,
      warningNum: "",
      host: this.$imgHost,
      purchaseList: [],
      exigencyNum: "",
      openWarning: false,
      form: {
        productName: {
          tag: "el-input",
          label: "产品名称",
          value: "",
          props: {
            clearable: true,
            placeholder: "请输入产品名称",
          },
        },
        productCode: {
          tag: "el-input",
          label: "产品编码",
          value: "",
          props: {
            clearable: true,
            placeholder: "请输入产品编码",
          },
        },
        // directoryId: this.formDirectoryId(),
        areaId: this.formArea(),
        // areaId: {
        //   tag: "el-select",
        //   label: "区域",
        //   value: 56,
        //   items: [
        //     {label: "西安2仓", value: 56},
        //   ],
        //   props: {},
        // },
        authority:[],
        state: {
          tag: "el-select",
          label: "库存状态",
          value: 0,
          items: [
            {label: "有库存", value: 1},
            {label: "无库存", value: 0},
          ],
          props: {},
        },
        stockStatus: {
          tag: "el-select",
          label: "状态",
          value: 3,
          items: [
            {label: "紧急补货", value: 3},
            {label: "库存警告", value: 2},
            {label: "正常", value: 1},
          ],
          props: {},
        },
      },
    };
  },
  created() {
    const {authorityList = []} = quinn.getStorage('userData')
    this.authority = authorityList
    this.$api.areaLedgerAreaList().then(res => {
      this.areaList = res
    })
    this.$api.purchaseGetPurchaseList({pageNumber: 1, pageSize: 100000}).then(res => {
      this.purchaseList = res.data
    })
    document.addEventListener('paste', this.handlePaste)
  },
  computed: {
    ...mapState(["userData"]),
    btnAuth() {
      const {authority = []} = this.userData || {};
      return authority.includes(192);
    },
    headers() {
      const token = this.token || this.$quinn.getStorage("token");
      return {
        token,
        pId: 1,
        pImg: this.preSalesImg.toString()
      };
    },
  },
  methods: {
    handlePaste(event) {
      if (!this.dialogVisible) return;
      const clipboardData = event.clipboardData || window.clipboardData;
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i];

          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile();
            if (file) {
              this.uploadImage(file);
            }
          } else {
            this.$message.error('请拷贝图片!');
            break;
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData();
      formData.append('file', imageFile);
      axios.post(`${this.$apiHost}/common/fileImgUrl`, formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
          'token': store.state.token
        }
      })
          .then(response => {
            this.preSalesImg.push(response.data.result[0]);
            // this.preSalesImgList.push('https://' + response.data.result[0]);
          })
          .catch(error => {
          });
    },
    exportDialog() {
      this.dialogVisible = true
      this.preSalesImg = []
    },
    deletePic(i) {
      this.preSalesImg.splice(i, 1)
    },
    onError(e) {
      this.loading = false;
      this.$message("导入失败");
    },
    onSuccess(res) {
      if (res.code != 200) {
        this.$message(res.msg);
      } else {
        this.$message({message: "导入成功！", type: "success"});
        this.componentKey += 1
      }
      this.dialogVisible = false
      this.loading = false;
    },
    onBefore(file) {
      // 检查 uploadData 中的参数是否为空
      if (!this.preSalesImg.toString()) {
        this.$message.error('请先填写其他信息！');
        return false; // 返回 false，阻止上传
      }

      // 进行文件类型和大小检查
      const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
      if (!isExcel) {
        this.$message.error('只能上传Excel文件');
        return false; // 返回 false，阻止上传
      }
      const isLt500KB = file.size / 1024 < 500;
      if (!isLt500KB) {
        this.$message.error('文件大小不能超过500KB');
        return false; // 返回 false，阻止上传
      }

      // 如果所有检查都通过，则允许上传
      return true;
    },
    handleClose() {
      this.openWare = false
    },
    handleAction(opts, row) {
      if (opts === "modifyCount") this.showDialog(opts, row);
      if (opts === "modifyWarePosition") {
        this.$api.inventoryGetLocationName().then(res => {
          this.positionList = res
        })
        this.ids = row.id
        // if (row.warehousePosition) {
        //   this.warehousePosition = row.warehousePosition.split(',')
        // } else {
        //   this.warehousePosition = []
        // }
        this.openWare = true
      }
      if (opts === "modifyWarning") {
        this.ids = row.id
        this.areaId = row.area
        this.materialId = row.materialId
        this.openWarning = true
        this.warningNum = row.warningNum
        this.exigencyNum = row.exigencyNum
      }
    },
    submitWarning() {
      if (this.exigencyNum > this.warningNum) return this.$message({message: "紧急补货值不可大于预警值！"})
      const data = {
        warningNum: this.warningNum,
        exigencyNum: this.exigencyNum,
        areaId: this.areaId,
        materialId: this.materialId
      }
      this.$api.inventoryUpdateInventoryWarningNum(data).then(res => {
        if (res == 1) {
          this.$message({message: "操作成功！", type: "success"})
          this.openWarning = false

          this.componentKey += 1
        }
      })
    },
    async defaultInventory(val) {
      this.$message({message: "数据量较大，请耐心等候！", type: "warning"})
      try {
        const params = {
          pageSize: 1000000,
          pageNumber: 1,
          areaId: val,
          sort: 1,
        };
        const res = await this.$api.inventoryGetInventoryList(params);
        const downData = res.data;

        function getWarehouse(val) {
          switch (val) {
            case 43:
              return '宁乡壹';
            case 44:
              return '广东仓';
            case 45:
              return '广西仓';
            case 52:
              return '贵州仓';
            case 53:
              return '云南仓';
            case 56:
              return '西安2仓';
            case 58:
              return '山西仓';
            default:
              return '未知仓库';
          }
        }

        const data = downData.map(a => ({
          区域: getWarehouse(a.area),
          产品编码: a.productCode,
          产品名称: a.productName,
          规格: a.norms,
          单位: a.unit,
          颜色: a.colour,
          库存: a.count,
        }));
        const sheetName = getWarehouse(val) + '库存明细';
        const wb = XLSX.utils.book_new();
        const sheet = XLSX.utils.json_to_sheet(data);
        sheet['!cols'] = [
          {wpx: 100}, // 区域
          {wpx: 100}, // 产品编码
          {wpx: 200}, // 产品名称
          {wpx: 150}, // 规格
          {wpx: 100}, // 单位
          {wpx: 100}, // 颜色
          {wpx: 100}  // 库存
        ];
        XLSX.utils.book_append_sheet(wb, sheet, sheetName);
        const wbout = XLSX.write(wb, {bookType: 'xlsx', type: 'binary'});
        const blob = new Blob([s2ab(wbout)], {type: 'application/octet-stream'});
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `${getWarehouse(val)}库存明细${new Date().getTime()}.xlsx`;
        link.click();
        URL.revokeObjectURL(link.href);
      } catch (error) {
        console.error('Error generating inventory report:', error);
      }

      function s2ab(s) {
        const buf = new ArrayBuffer(s.length);
        const view = new Uint8Array(buf);
        for (let i = 0; i < s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF;
        }
        return buf;
      }
    },
    // pushWareList() {
    //   this.addWareList = [...this.addWareList, {
    //     warehousePosition: "",
    //   }]
    // },
    // deleteProduce(list, index) {
    //   list.splice(index, 1)
    // },
    submit() {
      const data = {
        // warehousePosition: this.warehousePosition,
        id: this.ids
      }
      this.$api.inventoryUpdateLocationName(data).then(res => {
        if (res == 1) {
          this.$message({message: "操作成功！", type: "success"})
          this.openWare = false
          // window.location.reload(true);
          this.componentKey += 1
        }
      })
    }
  },
};
</script>

<style lang="less" scoped></style>

